#include "SystemWidget.h"
#include "StyleLoader.h"
#include <QScrollArea>
#include <QFrame>
#include <QFontDatabase>
#include <QSysInfo>
#include <QApplication>
#include <QScreen>
#include <QDebug>
#include <QMessageBox>
#include <QTranslator>
#include "log.h"

SystemWidget::SystemWidget(QWidget *parent)
    : QWidget{parent}
{
    initData();
    setupForm();
    applyStyles();
}

SystemWidget::~SystemWidget()
{
    saveData();
}

void SystemWidget::setupForm()
{
    // 创建主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setSpacing(15);
    mainLayout->setContentsMargins(20, 20, 20, 20);
    
    // 创建滚动区域
    QScrollArea *scrollArea = new QScrollArea(this);
    scrollArea->setWidgetResizable(true);
    scrollArea->setFrameShape(QFrame::NoFrame);
    scrollArea->setStyleSheet("QScrollArea { border: none; background: transparent; }");
    
    QWidget *scrollContent = new QWidget();
    QVBoxLayout *scrollLayout = new QVBoxLayout(scrollContent);
    scrollLayout->setSpacing(15);
    scrollLayout->setContentsMargins(0, 0, 0, 0);
    
    // 设置字体设置
    setupFontSettings();
    scrollLayout->addWidget(fontGroup);
    
    // 设置语言设置
    setupLanguageSettings();
    scrollLayout->addWidget(languageGroup);
    
    // 设置系统信息
    setupSystemInfo();
    scrollLayout->addWidget(systemInfoGroup);
    
    // 设置窗口设置
    setupWindowSettings();
    scrollLayout->addWidget(windowGroup);
    
    scrollLayout->addStretch();
    
    scrollArea->setWidget(scrollContent);
    mainLayout->addWidget(scrollArea);
    
    // 按钮布局
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    buttonLayout->setSpacing(10);
    buttonLayout->addStretch();
    
    btnReset = new QPushButton("恢复默认", this);
    btnReset->setProperty("styleClass", "secondary");
    btnReset->setFixedSize(100, 35);
    buttonLayout->addWidget(btnReset);
    
    btnApply = new QPushButton("应用", this);
    btnApply->setProperty("styleClass", "primary");
    btnApply->setFixedSize(100, 35);
    buttonLayout->addWidget(btnApply);
    
    btnClose = new QPushButton("关闭", this);
    btnClose->setProperty("styleClass", "secondary");
    btnClose->setFixedSize(100, 35);
    buttonLayout->addWidget(btnClose);
    
    mainLayout->addLayout(buttonLayout);
    
    // 连接信号槽
    connect(btnApply, &QPushButton::clicked, this, &SystemWidget::onSaveDataBtn);
    connect(btnClose, &QPushButton::clicked, this, &SystemWidget::sigClose);
    connect(btnReset, &QPushButton::clicked, this, &SystemWidget::onResetToDefault);
    
    connect(fontFamilyCombo, QOverload<const QString &>::of(&QComboBox::currentTextChanged),
            this, &SystemWidget::onFontFamilyChanged);
    connect(fontSizeSpin, QOverload<int>::of(&QSpinBox::valueChanged),
            this, &SystemWidget::onFontSizeChanged);
    connect(fontBoldCheck, &QCheckBox::stateChanged,
            this, &SystemWidget::onFontBoldChanged);
    connect(fontItalicCheck, &QCheckBox::stateChanged,
            this, &SystemWidget::onFontItalicChanged);
    connect(fontUnderlineCheck, &QCheckBox::stateChanged,
            this, &SystemWidget::onFontUnderlineChanged);
    connect(languageCombo, QOverload<const QString &>::of(&QComboBox::currentTextChanged),
            this, &SystemWidget::onLanguageChanged);
}

void SystemWidget::setupFontSettings()
{
    fontGroup = new QGroupBox("字体设置", this);
    QGridLayout *fontLayout = new QGridLayout(fontGroup);
    fontLayout->setSpacing(10);
    fontLayout->setContentsMargins(15, 15, 15, 15);
    
    // 字体族
    QLabel *fontFamilyLabel = new QLabel("字体:", fontGroup);
    fontFamilyCombo = new QComboBox(fontGroup);
    fontFamilyCombo->setEditable(false);
    QFontDatabase fontDb;
    QStringList fontFamilies = fontDb.families();
    fontFamilyCombo->addItems(fontFamilies);
    fontLayout->addWidget(fontFamilyLabel, 0, 0);
    fontLayout->addWidget(fontFamilyCombo, 0, 1, 1, 2);
    
    // 字体大小
    QLabel *fontSizeLabel = new QLabel("大小:", fontGroup);
    fontSizeSpin = new QSpinBox(fontGroup);
    fontSizeSpin->setRange(8, 72);
    fontSizeSpin->setSuffix(" pt");
    fontLayout->addWidget(fontSizeLabel, 1, 0);
    fontLayout->addWidget(fontSizeSpin, 1, 1);
    
    // 字体样式
    fontBoldCheck = new QCheckBox("粗体", fontGroup);
    fontItalicCheck = new QCheckBox("斜体", fontGroup);
    fontUnderlineCheck = new QCheckBox("下划线", fontGroup);
    fontLayout->addWidget(fontBoldCheck, 1, 2);
    fontLayout->addWidget(fontItalicCheck, 2, 2);
    fontLayout->addWidget(fontUnderlineCheck, 3, 2);
    
    // 字体预览
    QLabel *previewLabel = new QLabel("预览:", fontGroup);
    fontPreviewLabel = new QLabel("AaBbCc 123 字体预览", fontGroup);
    fontPreviewLabel->setMinimumHeight(50);
    fontPreviewLabel->setStyleSheet("border: 1px solid #555; padding: 10px; background: #2C2C2E; border-radius: 4px;");
    fontLayout->addWidget(previewLabel, 2, 0);
    fontLayout->addWidget(fontPreviewLabel, 2, 1, 2, 1);
}

void SystemWidget::setupLanguageSettings()
{
    languageGroup = new QGroupBox("语言设置", this);
    QHBoxLayout *languageLayout = new QHBoxLayout(languageGroup);
    languageLayout->setContentsMargins(15, 15, 15, 15);
    
    QLabel *languageLabel = new QLabel("界面语言:", languageGroup);
    languageCombo = new QComboBox(languageGroup);
    languageCombo->addItem("简体中文", "zh_CN");
    languageCombo->addItem("繁體中文", "zh_TW");
    languageCombo->addItem("English", "en_US");
    languageCombo->addItem("한국어", "ko_KR");
    languageCombo->addItem("Tiếng Việt", "vi_VN");
    languageCombo->addItem("Español", "es_ES");
    languageCombo->addItem("Português", "pt_PT");
    languageCombo->addItem("Deutsch", "de_DE");
    languageCombo->addItem("Français", "fr_FR");
    languageCombo->addItem("Русский", "ru_RU");
    languageCombo->addItem("العربية", "ar_SA");
    
    languageLayout->addWidget(languageLabel);
    languageLayout->addWidget(languageCombo);
    languageLayout->addStretch();
}

void SystemWidget::setupSystemInfo()
{
    systemInfoGroup = new QGroupBox("系统信息", this);
    QGridLayout *infoLayout = new QGridLayout(systemInfoGroup);
    infoLayout->setSpacing(10);
    infoLayout->setContentsMargins(15, 15, 15, 15);
    
    // 操作系统
    osLabel = new QLabel("操作系统:", systemInfoGroup);
    osValueLabel = new QLabel(systemInfoGroup);
    osValueLabel->setStyleSheet("color: #4CAF50;");
    infoLayout->addWidget(osLabel, 0, 0);
    infoLayout->addWidget(osValueLabel, 0, 1);
    
    // Qt版本
    qtLabel = new QLabel("Qt版本:", systemInfoGroup);
    qtValueLabel = new QLabel(systemInfoGroup);
    qtValueLabel->setStyleSheet("color: #4CAF50;");
    infoLayout->addWidget(qtLabel, 1, 0);
    infoLayout->addWidget(qtValueLabel, 1, 1);
    
    // CPU信息
    cpuLabel = new QLabel("处理器:", systemInfoGroup);
    cpuValueLabel = new QLabel(systemInfoGroup);
    cpuValueLabel->setStyleSheet("color: #4CAF50;");
    infoLayout->addWidget(cpuLabel, 2, 0);
    infoLayout->addWidget(cpuValueLabel, 2, 1);
    
    // 屏幕信息
    memoryLabel = new QLabel("屏幕:", systemInfoGroup);
    memoryValueLabel = new QLabel(systemInfoGroup);
    memoryValueLabel->setStyleSheet("color: #4CAF50;");
    infoLayout->addWidget(memoryLabel, 3, 0);
    infoLayout->addWidget(memoryValueLabel, 3, 1);
    
    // 设置标签可以自动换行
    osValueLabel->setWordWrap(true);
    qtValueLabel->setWordWrap(true);
    cpuValueLabel->setWordWrap(true);
    memoryValueLabel->setWordWrap(true);
    
    loadSystemInfo();
    
    // 设置当前字体值到UI
    fontFamilyCombo->setCurrentText(m_font.family());
    fontSizeSpin->setValue(m_font.pointSize());
    fontBoldCheck->setChecked(m_font.bold());
    fontItalicCheck->setChecked(m_font.italic());
    fontUnderlineCheck->setChecked(m_font.underline());
    fontPreviewLabel->setFont(m_font);
}

void SystemWidget::setupWindowSettings()
{
    windowGroup = new QGroupBox("窗口设置", this);
    QVBoxLayout *windowLayout = new QVBoxLayout(windowGroup);
    windowLayout->setContentsMargins(15, 15, 15, 15);
    windowLayout->setSpacing(10);
    
    alwaysOnTopCheck = new QCheckBox("窗口始终置顶", windowGroup);
    startMinimizedCheck = new QCheckBox("启动时最小化", windowGroup);
    
    windowLayout->addWidget(alwaysOnTopCheck);
    windowLayout->addWidget(startMinimizedCheck);
}

void SystemWidget::loadSystemInfo()
{
    // 操作系统信息
    QString osInfo = QSysInfo::prettyProductName();
    if (osInfo.isEmpty()) {
        osInfo = QString("%1 %2").arg(QSysInfo::productType()).arg(QSysInfo::productVersion());
    }
    osValueLabel->setText(osInfo);
    
    // Qt版本
    QString qtVersion = QString("Qt %1 (%2)").arg(QT_VERSION_STR).arg(QSysInfo::buildAbi());
    qtValueLabel->setText(qtVersion);
    
    // CPU架构信息
    QString cpuInfo = QString("%1 / %2")
        .arg(QSysInfo::currentCpuArchitecture())
        .arg(QSysInfo::buildCpuArchitecture());
    cpuValueLabel->setText(cpuInfo);
    
    // 屏幕信息
    QScreen *screen = QApplication::primaryScreen();
    if (screen) {
        QSize screenSize = screen->size();
        qreal dpi = screen->logicalDotsPerInch();
        QString screenInfo = QString("%1x%2 @ %3 DPI")
            .arg(screenSize.width())
            .arg(screenSize.height())
            .arg(QString::number(dpi, 'f', 0));
        memoryValueLabel->setText(screenInfo);
    } else {
        memoryValueLabel->setText("未知");
    }
}

void SystemWidget::initData()
{
    // ✅ 使用ConfigService获取字体配置
    m_font = ConfigService::instance().getFont();
    m_currentLanguage = "zh_CN"; // 默认语言
    
    // 在setupForm之前无法设置UI，所以这些将在setupForm中设置
}

void SystemWidget::saveData()
{
    // ✅ 使用ConfigService保存字体配置
    ConfigService::instance().setFont(m_font);
    ConfigService::instance().saveConfig();
}

void SystemWidget::applyStyles()
{
    // 从QSS文件加载样式
    QString style = StyleLoader::loadDarkTheme();
    if (!style.isEmpty()) {
        setStyleSheet(style);
    } else {
        qWarning() << "警告：样式文件加载失败！请检查 resource.qrc 配置。";
    }
}

void SystemWidget::onFontFamilyChanged(const QString &family)
{
    m_font.setFamily(family);
    fontPreviewLabel->setFont(m_font);
}

void SystemWidget::onFontSizeChanged(int size)
{
    m_font.setPointSize(size);
    fontPreviewLabel->setFont(m_font);
}

void SystemWidget::onFontBoldChanged(int state)
{
    m_font.setBold(state == Qt::Checked);
    fontPreviewLabel->setFont(m_font);
}

void SystemWidget::onFontItalicChanged(int state)
{
    m_font.setItalic(state == Qt::Checked);
    fontPreviewLabel->setFont(m_font);
}

void SystemWidget::onFontUnderlineChanged(int state)
{
    m_font.setUnderline(state == Qt::Checked);
    fontPreviewLabel->setFont(m_font);
}

void SystemWidget::onLanguageChanged(const QString &language)
{
    QString langCode = languageCombo->currentData().toString();
    m_currentLanguage = langCode;
}

void SystemWidget::onSaveDataBtn()
{
    saveData();
    emit sigFontChanged();
    emit sigLanguageChanged();
    
    QMessageBox::information(this, "提示", "设置已保存！\n部分设置需要重启应用程序才能生效。");
}

void SystemWidget::onResetToDefault()
{
    int ret = QMessageBox::question(this, "确认", "确定要恢复默认设置吗？", 
                                     QMessageBox::Yes | QMessageBox::No);
    if (ret == QMessageBox::Yes) {
        // 恢复默认字体
        m_font = QFont("Microsoft YaHei", 10);
        
        // 更新UI
        fontFamilyCombo->setCurrentText(m_font.family());
        fontSizeSpin->setValue(m_font.pointSize());
        fontBoldCheck->setChecked(m_font.bold());
        fontItalicCheck->setChecked(m_font.italic());
        fontUnderlineCheck->setChecked(m_font.underline());
        fontPreviewLabel->setFont(m_font);
        
        // 恢复默认语言
        languageCombo->setCurrentIndex(0);
        m_currentLanguage = "zh_CN";
        
        // 恢复窗口设置
        alwaysOnTopCheck->setChecked(false);
        startMinimizedCheck->setChecked(false);
        
        QMessageBox::information(this, "提示", "已恢复默认设置！");
    }
}
